<template>
  <div class="container">
    <!-- 热销商品 -->
    <section class="hot-products">
      <h2>🔥 热销商品</h2>
      <div class="card-container">
        <el-card
          v-for="(item, index) in hotProducts"
          :key="index"
          class="product-card"
        >
          <div class="image-container">
            <img :src="item.coverpicture || defaultImage" style="margin-bottom: 20px" class="card-image" />
          </div>
          <div class="product-info">
            <p class="product-name">{{ item.pname }}</p>
            <p class="product-name">{{ item.description }}</p>
            <p class="product-price">￥{{ item.price }}</p>
            <p class="product-stock">库存: {{ item.stock }} 件</p>
            <el-button type="success" plain @click="handleBuy(item)">
              购买
            </el-button>
          </div>
        </el-card>
      </div>
    </section>

    <!-- 热销民宿 -->
    <section class="hot-minsu">
      <h2>🏡 热销民宿</h2>
      <div class="card-container">
        <el-card
          v-for="(minsu, index) in hotMinsu"
          :key="index"
          class="minsu-card"
        >
          <div class="image-container">
            <img :src="minsu.coverpicture || defaultImage" class="card-image" />
          </div>
          <div class="product-info">
            <p class="name">{{ minsu.hname }}</p>
            <p class="price">价格: ￥{{ minsu.price }} / 晚</p>
            <p class="rating">评分: {{ minsu.grade }} ⭐</p>
            <p class="stock" :class="{ 'low-stock': minsu.stock < 5 }">
              库存: {{ minsu.stock }} {{ minsu.stock < 5 ? '(库存紧张)' : '' }}
            </p>
            <el-button type="success" plain @click="reserveMinsu(minsu)">
              预订
            </el-button>
          </div>
        </el-card>
      </div>
    </section>

    <!-- 个性推荐 -->
    <section class="recommended-products">
      <h2>🎉 个性推荐 🎁</h2>
      <div class="card-container">
        <el-card
          v-for="(item, index) in recommendedProducts"
          :key="index"
          class="product-card"
        >
          <div class="image-container">
            <img :src="item.coverpicture || defaultImage" style="margin-bottom: 20px" class="card-image" />
          </div>
          <div class="product-info">
            <p class="product-name">{{ item.pname }}</p>
            <p class="product-name">{{ item.description }}</p>
            <p class="product-price">💰 ￥{{ item.price }}</p>
            <p class="product-stock">📦 库存: {{ item.stock }} 件</p>
            <el-button type="success" plain @click="handleBuy(item)">
              🛒 购买
            </el-button>
          </div>
        </el-card>
      </div>
    </section>

    <!-- 购买成功弹窗 -->
    <el-dialog title="购买成功" :visible.sync="isPurchased" width="30%" center>
      <p>{{ purchaseMessage }}</p>
    </el-dialog>

    <!-- 预订成功弹窗 -->
    <el-dialog title="预订成功" :visible.sync="showReserveDialog" width="30%" center>
      <p>您已成功预订 {{ reservedMinsu.hname }}</p>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="showReserveDialog = false">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getProductSelling, handleBuy, getHotelSelling, getRecommendProduct } from "@/api/market.ts";
import { bookHomeStay } from "@/api/homestay.ts";

export default {
  data() {
    return {
      hotProducts: [], // 热销商品
      hotMinsu: [], // 热销民宿
      recommendedProducts: [], // 个性推荐商品
      defaultImage: "https://via.placeholder.com/250x200?text=Image",
      isPurchased: false,
      purchaseMessage: "",
      showReserveDialog: false,
      reservedMinsu: {},
    };
  },
  mounted() {
    this.fetchHotProducts();
    this.fetchHotMinsu();
    this.fetchRecommendedProducts(); // 获取个性推荐商品
  },
  methods: {
    // 获取热销商品
    async fetchHotProducts() {
      try {
        const response = await getProductSelling();
        if (response?.data?.data) {
          this.hotProducts = response.data.data
            .sort((a, b) => b.sales - a.sales) // 按销量降序
            .slice(0, 11); // 取前6个热销商品
        }
      } catch (error) {
        console.error("获取商品数据失败:", error);
      }
    },

    // 获取热销民宿
    async fetchHotMinsu() {
      try {
        const response = await getHotelSelling();
        if (response?.data?.data) {
          this.hotMinsu = response.data.data
            .sort((a, b) => b.sales - a.sales) // 按销量降序
        }
      } catch (error) {
        console.error("获取民宿数据失败:", error);
      }
    },

    // 获取个性推荐商品
    async fetchRecommendedProducts() {
      try {
        const response = await getRecommendProduct();
        if (response?.data?.data) {
          this.recommendedProducts = response.data.data
            .sort((a, b) => b.recommendScore - a.recommendScore) // 按推荐分数降序
            .slice(0, 6); // 取前6个推荐商品
        }
      } catch (error) {
        console.error("获取推荐商品数据失败:", error);
      }
    },

    // 购买商品
    async handleBuy(item) {
      try {
        await handleBuy({
          uid: JSON.parse(localStorage.getItem("currentUser")).uid,
          pid: item.pid,
          fid: item.fid,
          pname: item.pname,
        });
        this.purchaseMessage = `成功购买 ${item.pname}`;
        this.isPurchased = true;
        this.fetchHotProducts(); // 刷新热销商品
        this.fetchRecommendedProducts(); // 刷新推荐商品
      } catch (error) {
        console.error("购买失败:", error);
      }
    },

    // 预订民宿
    async reserveMinsu(minsu) {
      const formData = new FormData();
      formData.append(
        "bookhotelrecord",
        JSON.stringify({
          hid: minsu.hid,
          uid: JSON.parse(localStorage.getItem("currentUser")).uid,
          hname: minsu.hname,
          fid: minsu.fid,
        })
      );
      try {
        const res = await bookHomeStay(formData);
        if (res.data.code === 1) {
          this.reservedMinsu = minsu;
          this.showReserveDialog = true;
          this.fetchHotMinsu(); // 刷新热销民宿
        } else {
          this.$message.error(res.data.message || "预定失败！");
        }
      } catch (error) {
        console.error("预订失败", error);
      }
    },
  },
};
</script>
<style scoped>
.container {
  padding: 20px;
}

/* 热销商品、热销民宿和个性推荐的标题 */
h2 {
  text-align: center;
  margin-bottom: 20px;
}

/* 统一卡片容器 */
.card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: left;
}

/* 商品卡片 */
.product-card,
.minsu-card {
  width: 250px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  transition: transform 0.2s;
}

.product-card:hover,
.minsu-card:hover {
  transform: translateY(-5px);
}

/* 图片区域 */
.image-container {
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.card-image {
  width: 55%;
  object-fit: cover;
}

/* 信息区域 */
.product-info {
  padding: 10px;
  text-align: center;
}

.product-name,
.name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.product-price,
.price {
  font-size: 14px;
  color: #e53935;
}

.stock {
  font-size: 12px;
  color: #388e3c;
}

.low-stock {
  color: red;
}

.actions {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
</style>